package com.loobot.album.config.secure.gateway;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.loobot.album.exception.AppException;
import com.loobot.album.net.ErrorCode;
import com.loobot.album.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @author: Ike.Fan
 * @date: 2019/3/4.
 */
@Component
public class LoobotToken {
    private static final String SECRET = "2019";

    //name and password, usually for user
    public String getToken(){
        return JWT.create().withAudience("loobot")
                .sign(Algorithm.HMAC256("123456"));
    }

    //name and password, usually for user
    public boolean checkToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw AppException.getException(ErrorCode.NEED_AUTHORD);
        }
        return true;
    }

    //loobot account
    public  String getTokenContainInfo(LoobotAccount loobotAccount){
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,loobotAccount.viableMinutes);
        Date expiresDate = nowTime.getTime();

        String token = JWT.create()
                .withClaim("info", JsonUtils.toJson(loobotAccount))
                .withExpiresAt(expiresDate)
                .withIssuedAt(iatDate)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public  LoobotAccount verifyToken( String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
//        System.out.println("info=" +  jwt.getClaim("info").asString());
        try{
            jwt = verifier.verify(token);
            return JsonUtils.fromJsonObject(jwt.getClaim("info").asString(), LoobotAccount.class);
        }catch (Exception e){
            throw AppException.getException(ErrorCode.NEED_AUTHORD);
        }
    }
}
